package net.sureon.common.security;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sureon.common.I18nSupport;

/**
 * roles, a roles include a list of privileges.
 * 
 * @author jason
 * 
 */
public class Role {
	public static final Role COMPANY_ADMIN, GROUP_ADMIN, MEMBER, ROOT;
	public static final String ROLE_NAME_MEMBER = "Memeber";
	public static final String ROLE_NAME_GROUPADMIN = "GroupAdmin";
	public static final String ROLE_NAME_COMPAYADMIN = "CompanyAdmin";
	public static final String ROLE_NAME_ROOT = "Root";
	
	private static Map<String, Role> predefinedRoles = new HashMap<String, Role>();

	public static List getPredefinedRoles() {
		return Arrays.asList(new Role[] { MEMBER,
				GROUP_ADMIN, COMPANY_ADMIN });
	}

	public static Role getRole(String roleName) {
		return predefinedRoles.get(roleName);
	}

	static {
		List<Privilege> memberPrivs = new ArrayList<Privilege>();
		memberPrivs.add(Privilege.USER_R);
		memberPrivs.add(Privilege.USER_W);
		memberPrivs.add(Privilege.GROUP_R);
		memberPrivs.add(Privilege.COMPANY_R);
		MEMBER = new Role(ROLE_NAME_MEMBER, memberPrivs);
		predefinedRoles.put(ROLE_NAME_MEMBER, MEMBER);

		List<Privilege> groupAdminPrivs = new ArrayList<Privilege>(memberPrivs);
		groupAdminPrivs.add(Privilege.GROUP_W);
		GROUP_ADMIN = new Role(ROLE_NAME_GROUPADMIN, groupAdminPrivs);
		predefinedRoles.put(ROLE_NAME_GROUPADMIN, GROUP_ADMIN);

		List<Privilege> companyAdminPrivs = new ArrayList<Privilege>(
				groupAdminPrivs);
		companyAdminPrivs.add(Privilege.COMPANY_W);
		COMPANY_ADMIN = new Role(ROLE_NAME_COMPAYADMIN, companyAdminPrivs);
		predefinedRoles.put(ROLE_NAME_COMPAYADMIN, COMPANY_ADMIN);
		
		ROOT = new Role(ROLE_NAME_ROOT, companyAdminPrivs);
		predefinedRoles.put(ROLE_NAME_ROOT, ROOT);

	}
	private String name;
	private List<Privilege> privileges;

	private Role(String name, List<Privilege> privs) {
		this.name = name;
		this.privileges = Collections.unmodifiableList(privs);
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}
	
	public String getTranslatedName() {
		return I18nSupport.getMessage(getName());
	}

	public boolean isPrivInRole(Privilege priv) {
		return privileges.contains(priv);
	}

	/**
	 * @return the privileges
	 */
	public List<Privilege> getPrivileges() {
		return privileges;
	}

	public String toString() {
		return "Role:" + name;
	}
}
